'use strict';

const PROP_QUIZZES = 'quizzes'; 
let tabLimit = 1
    ,startAutoWorking = false
    ,working = false
    ,quizIndex = 0  // 记录quiz的index
    ,shouldDownloadAll = true // 是否打开下一个quiz
    ;


/**
 * 打开标签页
 * @param {String} url 
 * @param {Function} callback 
 */
const openTab = (url,callback)=>{
    chrome.tabs.query({},tabs=>{
        for(let i =0;i<tabs.length;i++){
            const tab = tabs[i]
            if(tab.width<376){  // 手机模式的标签页
                chrome.tabs.update(tab.id,{
                    url: url,
                    active: true,
                },tab=>{
                    callback&&callback(tab)
                })
                break;
            }
        }
    })
}

/**
 * 提取图片名称
 * @param {String} url 
 * @returns {String}
 */
const getFileName = url=>{
    const a = url.lastIndexOf('/')+1;
    const b = url.indexOf('?');
    if(b!=-1){
        return url.slice(a,b)
    }else{
        return url.slice(a)
    }
}

const getCachedQuizzes = ()=>JSON.parse(localStorage.getItem(PROP_QUIZZES))||[]
const setCachedQuizzes = quizzes=>localStorage.setItem(PROP_QUIZZES,JSON.stringify(quizzes))

const openQuizPage = ()=>{ // 打开quiz页同时将quinz_index++
    const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES)) || []
    const quiz = quizzes[quizIndex++];  
    if(quiz&&!quiz.done){
    // if(quiz&&quiz.options){
        // const url = quiz.url.replace('/test/','/results/');
        const url = quiz.url
        openTab(url,tab=>{
            console.log('访问quiz二页',tab)
        })
        return true
    }else{
        return false
    } 
}

/**
 * 打开指定index的quiz页面
 * @param {Object} quiz
 */
const openOneQuizPage = quiz=> {
    if(quiz){
        const url = quiz.url
        openTab(url,tab=>{
            console.log('打开quiz页',tab.id)
        })
        return true
    }else{
        return false
    }   
}

const donwloadQuizThumb = (quiz)=>{
    let p = new Promise((resolve,reject)=>{
        if(quiz&&typeof quiz=='object'){
            const shouldDownload = quiz.thumb&&!quiz.local_thumb?true:false;
            if(shouldDownload){ // 下载thumb
                const date = new Date();
                const thumb = quiz.thumb
                const filename = `quizzes/${quiz.id}/${Math.random().toString(32).slice(2)}`+getFileName(thumb)
                console.log(thumb,'图片保存路径',filename)
                chrome.downloads.download({
                    url: thumb,
                    filename: filename
                },(id)=>{
                    quiz.local_thumb = filename   
                    resolve(quiz)
                    console.log(id+',quiz thumb下载完成')                                   
                })
            
            }else{
                resolve({
                    err: 'can not download thumbs'
                })
            }
        }else{
            reject({
                err: 'quiz must be a object'
            })
        }
    })
    return p;
}

/**
 * 下载quiz 选项封面图片
 * @param {Object} quiz 
 */
const donwloadQuizSelect = (quiz)=>{
    let p = new Promise((resolve,reject)=>{
        if(quiz&&typeof quiz=='object'){
            const select = quiz.select
            const shouldDownload = select&&select.thumb&&!select.local_thumb;
            if(shouldDownload){ // 下载select thumb
                const date = new Date();
                const thumb = select.thumb
                const filename = `quizzes/${quiz.id}/${Math.random().toString(32).slice(2)}_`+getFileName(thumb)
                console.log(thumb,'图片保存路径',filename)
                chrome.downloads.download({
                    url: thumb,
                    filename: filename
                },(id)=>{
                    select.local_thumb = filename   
                    resolve({
                        msg: 'success',
                        data: quiz
                    })
                    console.log(id+'select thumb下载完成')                                     
                })
                
            }else{
                resolve({
                    err: 'can not download thumbs'
                })
            }
        }else{
            reject({
                err: 'quiz must be a object'
            })
        }
    })
    return p;
}

/**
 * 下载quiz result图片
 * @param {Object} quiz 
 */
const downLoadQuizResults = quiz=>{
    let p = new Promise((resolve,reject)=>{
        if(quiz&&typeof quiz=='object'){
            // const shouldDownload = quiz.results&&!quiz.local_results?true:quiz.results&&quiz.local_results&&quiz.results.length>quiz.local_results.length?true:false;
            const shouldDownload = true
            delete quiz.local_results
            if(shouldDownload){ // 下载results
                const date = new Date();
                for(let i in quiz.results){ 
                    const result = quiz.results[i];                
                    const filename = `quizzes/${quiz.id}/${Math.random().toString(32).slice(2)}_`+getFileName(result.pic)
                    chrome.downloads.download({
                        url: result.pic,
                        filename: filename
                    },(id)=>{
                        quiz.local_results = quiz.local_results || []
                        quiz.local_results[i] = {
                             pic: filename,
                            desc: result.desc
                        };
                        console.log(i,Object.assign({},quiz.local_results))
                        const completeResults = quiz.local_results.filter(res=>{if(res){return true}})
                        if(completeResults.length===quiz.results.length){
                            console.log(i+'个结果的图片下载完成')
                            resolve({
                                msg:'success',
                                data:quiz
                            })
                        }               
                    })
                }
            }else{
                resolve({
                    err: 'can not download'
                })
            }
        }else{
           reject({
               err: 'quiz must be a object'
           })
        }
    })
    return p;
}

const startSpider = ()=>{
    const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES)) || []
/*     while (tabLimit>tabCount&&i<quizzes.length) {        
        const r = openQuizPage()
        if(r) tabCount++;   
        console.log(`打开第${i}个quiz页面`)
    } */
    while (quizIndex<quizzes.length&&!working) {        
        const r = openQuizPage()
        if(r){  // quiz页面成功打开
            working = true;
        }
        console.log(`打开第${quizIndex}个quiz页面`)
    }
}


let loadingState = false
const startDownload = async (i=0)=>{ // 下载图片
    if(loadingState){
        console.log('正在下载中')
        return false;
    }
        
    const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES)) || []
    if(quizzes.length>i){
        const quiz = quizzes[i]
        try {
            await donwloadQuizThumb(quiz); // 下载quiz封面
            await donwloadQuizSelect(quiz); // 下载quiz select 封面 
            await downLoadQuizResults(quiz); // 下载quiz results           
            localStorage.setItem(PROP_QUIZZES,JSON.stringify(quizzes)); // 更新本地数据        
            console.log(`第${i}个quiz图片下载完成`)
            loadingState = false;
            startDownload(i+1)  // 递归下载下一个quiz     
        }catch(err){
            console.error(err)
            startDownload(i+1)  // 出错则下载下一个quiz 
        }   
    }else{
        console.log('所有quiz图片下载完成')
    }

}

// 仅下载一个quiz
const crawlOneQuiz = async (i)=>{
    shouldDownloadAll = false
    const quizzes = getCachedQuizzes()
    const quiz = quizzes[i]
    if(quiz){
        delete quiz.done
        delete quiz.results
        setCachedQuizzes(quizzes);  // 删除采集到的results
        // console.log('清除旧的results',quiz)
        openOneQuizPage(quiz); // 打开quiz页
        chrome.runtime.onMessage.addListener(async (message,sender,response)=>{
            const tab = sender.tab
            switch (message.msg) {
                case 'next':
                    if(!shouldDownloadAll){  
                    //    await downloadOneQuizPic(i)
                       shouldDownloadAll = true;
                    }
                break;
                case "reload":
                    if(!shouldDownloadAll){
                        openOneQuizPage(quiz)
                    }
                break;
            }
        });
    }
}

const downloadOneQuizPic = async (i)=>{
    if(loadingState){
        console.log('正在下载中')        
        return false;
    }
        
    const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES)) || []
    if(quizzes.length>i){
        const quiz = quizzes[i]
        try {
            console.log('该下载thumb')
            await donwloadQuizThumb(quiz); // 下载quiz封面
            console.log('该下载select thumb')
            await donwloadQuizSelect(quiz); // 下载quiz select 封面 
            console.log('该下载result')
            await downLoadQuizResults(quiz); // 下载quiz results           
            localStorage.setItem(PROP_QUIZZES,JSON.stringify(quizzes)); // 更新本地数据        
            loadingState = false; 
        }catch(err){
            console.error(err)
        }   
    }else{
        console.log('所有quiz图片下载完成')
    }
}

/**
 * 发消息给tab页，可以开始干活了
 * @param {Object} tab 
 */
const startWorking = function (tab) {
    console.log('是否可以开始自动采集：',startAutoWorking)
    if(startAutoWorking){
        chrome.tabs.sendMessage(tab.id,{
            msg:'startWorking'
        })
    }
}

const btnAuto = document.querySelector('.btn-enable-auto')
const btnStart = document.querySelector('.btn-start')
const btnDownload = document.querySelector('.btn-download')
const commonList = document.querySelector('.common-list')
btnStart.addEventListener('click',()=>{   
    console.log('开始采集')
    startAutoWorking = true    
    openQuizPage()
})

btnDownload.addEventListener('click',()=>{
    startDownload()
})

commonList.addEventListener('click',async function (e) {
    const target = e.target;    

    if(target.className === "btn btn_download-quizz"){  // 下载图片
        const index = target.dataset.index;
        const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES));
        if(quizzes){
            await downloadOneQuizPic(index)
        }

    }else if(target.className === 'btn btn_query-quizz'){    // 采集结果
        startAutoWorking = true // 允许自动工作
        const index = target.dataset.index;
        const quizzes = JSON.parse(localStorage.getItem(PROP_QUIZZES));
        if(quizzes){
            var quiz = quizzes[index];
            delete quiz.local_results   
            delete quiz.local_thumb
            if(quiz.select){
                delete quiz.select.local_thumb
            }
            localStorage.setItem(PROP_QUIZZES,JSON.stringify(quizzes))
            await crawlOneQuiz(index)
        }
    }

})

chrome.runtime.onMessage.addListener((message,sender,response)=>{
    console.log('收到消息',message.msg)
    console.log('发送者',sender)
    const tab = sender.tab
    switch (message.msg) {
        case 'next':
            if(shouldDownloadAll){   // 判断是否继续下载下一个quiz
                working = false;
                startSpider();
            }
            break;
        case 'reload':
            if(shouldDownloadAll){
                if(quizIndex>0)quizIndex--;
                working = false
                startSpider()
            }
            break;
        case "pageOpened": // 页面打开
            startWorking(tab);
            break;
        default:
            break;
    }
})

function onload() {
    var list = document.querySelector('.common-list')
    var quizzes = JSON.parse(localStorage.getItem('quizzes'))
    var htmlStr = ''
    if(quizzes){
        for(var i =0;i<quizzes.length;i++){
            var quiz = quizzes[i]
            htmlStr += `<li><i>${i+1}</i><span>${quiz.title}</span><div>采集到的结果数量：${quiz.results?quiz.results.length:0}<button class="btn btn_query-quizz" data-index="${i}">采集Quiz</button><button class="btn btn_download-quizz" data-index="${i}">下载图片</button></div><div><a href="${quiz.url}">${quiz.url}</a></div><div>${JSON.stringify(quiz)}</div></li>`
        }
    }
    list.innerHTML = htmlStr;
}
onload()
chrome.downloads.onChanged.addListener(downloadDelta=>{
    if(downloadDelta.endTime){
        console.log(downloadDelta.id,'下载结束,endTime',downloadDelta.endTime)
    }
})
/* chrome.tabs.onRemoved.addListener((tabid,info)=>{   // 当tab被移除后，打开新的tab
    console.log(tabid,info,"关闭tab")
    if(tabCount>0){
        tabCount--;
   
        const quizzes = JSON.parse(localStorage.getItem('quizzes')) || []
        if(i<quizzes.length){   
            startSpider()
        }   
    } 
}); */
